﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Auction_Intranet.Models;
using AuctionDataLayer;

namespace Auction_Intranet.Controllers
{
    [HandleError]
    public class ProfileController : ParentController
    {

        DataRepository m_rep = new DataRepository();
        public ActionResult Index()
        {
            var username = (User.Identity.Name).Split('\\')[1];
            var user = m_rep.GetUserByUsername(username);
            if (user != null)
            {
                Group singleGroup = m_rep.GetGroupById(user.MyGroupId);
                if(singleGroup != null)
                {
                    ProfileModel model = new ProfileModel();
                    model.user = user;
                    model.singleGroup = singleGroup;

                    BidsListModel bids = new BidsListModel();                  
                    bids.userBids = m_rep.GetBidsByGroupId(user.MyGroupId);
                    bids.pendingBids = bids.userBids.Where(x => x.StateId == 1).Count();
                    bids.acceptedBids = bids.userBids.Where(x => x.StateId == 2).Count();
                    bids.declinedBids = bids.userBids.Where(x => x.StateId == 3).Count();
                    
                    model.singleBids = bids;

                    UserStatModel userStats = new UserStatModel();
                    userStats.userCredit = user.Balance;

                    List<UserInGroup> allUserInGroupForUser = m_rep.GetUserInGroupByUserID(user.Id).Where(x => x.GroupId != user.MyGroupId).ToList();
                    int availableUserInGroupCredit =  allUserInGroupForUser.Sum(x => (x.CreditAdded - x.CreditAddedSpent));//Get all user in group for this user and all groups and sum the (added-spent)
                    int investedPendingBidCredit = m_rep.GetUserInGroupBidsForActiveUserInGroup(user.Id).ToList().Sum(x => x.MembersCreditPaid);// Get all userInGroupBid that have active member and sum the credit spent
                    userStats.investedRefundable = availableUserInGroupCredit + investedPendingBidCredit;
                    
                    userStats.investedNonRefundable = m_rep.GetUserInGroupBidsForInactiveUserInGroup(user.Id).ToList().Sum(x => x.MembersCreditPaid);// Get all useringroupbid that have inactive member and sum the credit spent

                    userStats.spentCredit = m_rep.GetAcceptedUserInGroupBidsForUserInGroup(user.Id).ToList().Sum(x => x.MembersCreditPaid);

                    model.userStat = userStats;
                    return View(model);
                }
            }
            return View("NotFound");
        }
    }
}
